"use client"

import React, { useState, useEffect, Suspense } from 'react';
import type { AppProps } from 'next/app';
// import {NextUIProvider} from "@nextui-org/react";
import NProgress from 'nprogress';
import 'nprogress/nprogress.css'; // 这是 nprogress 的默认样式
import Router from 'next/router';
import {
    createFromIconfontCN,
    DesktopOutlined,
    FileOutlined,
    // PieChartOutlined,
    TeamOutlined,
    UserOutlined,
    HomeOutlined,
    LogoutOutlined,
    SettingOutlined,
} from '@ant-design/icons';
import type { MenuProps } from 'antd';
import { Breadcrumb, Layout, Menu, theme, Spin, Avatar, Dropdown, Space } from 'antd';
// import { Image } from "@nextui-org/react";
import "../app/globals.css";
import styles from './app.module.css'
import {AcmeLogo} from '../assets/svgs/icons';
import { useRouter } from 'next/router';
const {
    Header,
    Content,
    Footer,
    Sider
} = Layout;
type MenuItem = Required<MenuProps>['items'][number];
console.log('AcmeLogo', AcmeLogo);
// console.log('IconSvg', IconSvg);
const siderStyle: React.CSSProperties = {
    overflow: 'auto',
    height: '100vh',
    position: 'fixed',
    left: 0,
    top: 0,
    bottom: 0,
    scrollbarWidth: 'thin',
    scrollbarGutter: 'stable',
    zIndex: 1000,
    boxShadow: '2px 0 8px 0 rgba(29,35,41,.05)',
};
// const headStyle: React.CSSProperties = {
//     overflow: 'hidden',
//     height: '66px',
//     position: 'fixed',
//     insetInlineStart: 0,
//     top: 0,
//     scrollbarWidth: 'thin',
//     scrollbarGutter: 'stable',
//     zIndex: 1000
// };
const logoStyle: React.CSSProperties = {
    // width: '120px',
    // minWidth: '120px',
    height: '32px',
    background: 'rgba(255, 255, 255, .2)',
    borderRadius: '6px',
    margin: '16px',
    display: 'flex',
    justifyContent: 'center',
    alignItems: 'center',
    color: 'white',
    fontWeight: 'bold',
    fontSize: '16px',
    whiteSpace: 'nowrap',
    overflow: 'hidden',
    textOverflow: 'ellipsis',
    wordBreak: 'break-all'
    // textEmphasis: ''
    // marginInlineEnd: '24px'
}
const MyIcon = createFromIconfontCN({
    scriptUrl: '//at.alicdn.com/t/c/font_4689687_zuo9d43u9oh.js', // 在 iconfont.cn 上生成
});
function getItem(
    label: React.ReactNode,
    key: React.Key,
    icon?: React.ReactNode,
    children?: MenuItem[],
): MenuItem {
    return {
        key,
        icon,
        children,
        label,
    } as MenuItem;
}

const items: MenuItem[] = [
    getItem('首页', '/home', <HomeOutlined />),
    getItem('示例页面', '/example', <DesktopOutlined />),
    getItem('用户管理', 'user', <UserOutlined />, [
        getItem('用户列表', '/user/list', <TeamOutlined />),
        getItem('用户设置', '/user/settings', <MyIcon type='icon-docjpge-fill' />),
    ]),
    getItem('系统管理', 'system', <TeamOutlined />, [
        getItem('角色管理', '/system/roles', <TeamOutlined />),
        getItem('权限设置', '/system/permissions', <TeamOutlined />)
    ]),
    getItem('文件管理', '/files', <FileOutlined />),
];

// 在页面切换时显示进度条
Router.events.on('routeChangeStart', () => {
    NProgress.start();
});

Router.events.on('routeChangeComplete', () => {
    NProgress.done();
});

Router.events.on('routeChangeError', () => {
    NProgress.done();
});

// 添加面包屑映射配置
const breadcrumbNameMap: Record<string, string> = {
    '/home': '首页',
    '/example': '示例页面',
    '/user': '用户管理',
    '/user/list': '用户列表',
    '/user/settings': '用户设置',
    '/system': '系统管理',
    '/system/roles': '角色管理',
    '/system/permissions': '权限设置',
    '/files': '文件管理',
};

// 更新基础布局样式
const baseLayoutStyle: React.CSSProperties = {
    minHeight: '100vh',
    position: 'relative',
    background: '#f5f5f5', // 改用浅灰色背景
};

const mainContentStyle: React.CSSProperties = {
    position: 'relative',
    transition: 'padding-left 0.2s cubic-bezier(0.4, 0, 0.2, 1)',
    minHeight: '100vh',
    paddingLeft: '200px',
    background: '#ffffff', // 添加白色背景
};

const mainContentCollapsedStyle: React.CSSProperties = {
    position: 'relative',
    transition: 'padding-left 0.2s cubic-bezier(0.4, 0, 0.2, 1)',
    minHeight: '100vh',
    paddingLeft: '80px',
    background: '#ffffff', // 添加白色背景
};

const innerContentStyle: React.CSSProperties = {
    width: '100%',
    maxWidth: '100%',
    margin: '0 auto',
    minHeight: '100vh', // 确保最小高度
    background: '#ffffff', // 添加白色背景
};

const userMenuItems = [
    {
        key: 'profile',
        icon: <UserOutlined />,
        label: '个人信息',
    },
    {
        key: 'settings',
        icon: <SettingOutlined />,
        label: '修改设置',
    },
    {
        type: 'divider',
    },
    {
        key: 'logout',
        icon: <LogoutOutlined />,
        label: '退出登录',
    },
];

export default function App(props: AppProps) {
    const { Component, pageProps } = props;
    const router = useRouter();
    const [loading, setLoading] = useState(false);
    const [collapsed, setCollapsed] = useState(false);
    const [mounted, setMounted] = useState(false);

    const {
        token: {
            colorBgContainer,
            borderRadiusLG,
            blue1
        },
    } = theme.useToken();

    // 添加挂载效果
    useEffect(() => {
        setMounted(true);
    }, []);

    // 路由变化处理
    useEffect(() => {
        const handleStart = () => {
            NProgress.start();
            setLoading(true);
        };

        const handleComplete = () => {
            NProgress.done();
            setLoading(false);
        };

        Router.events.on('routeChangeStart', handleStart);
        Router.events.on('routeChangeComplete', handleComplete);
        Router.events.on('routeChangeError', handleComplete);

        return () => {
            Router.events.off('routeChangeStart', handleStart);
            Router.events.off('routeChangeComplete', handleComplete);
            Router.events.off('routeChangeError', handleComplete);
        };
    }, []);

    // 如果还没有挂载，显示一个简单的加载状态
    if (!mounted) {
        return (
            <div style={{
                height: '100vh',
                width: '100vw',
                display: 'flex',
                justifyContent: 'center',
                alignItems: 'center',
                background: '#ffffff',
            }}>
                <Spin size="large" />
            </div>
        );
    }

    console.log('props', props);
    console.log('Component', Component);
    console.log('loading', loading);
    const handleMenuClick = ({ key }: { key: string }) => {
        if (key.startsWith('/')) {
            router.push(key);
        }
    };

    // 添加生成面包屑的函数
    const generateBreadcrumbs = () => {
        const paths = router.pathname.split('/').filter(Boolean);
        const breadcrumbs = [];
        let url = '';

        // 添加首页
        breadcrumbs.push(
            <Breadcrumb.Item key="home" onClick={() => router.push('/home')} className={styles.breadcrumbItem}>
                <HomeOutlined /> 首页
            </Breadcrumb.Item>
        );

        // 添加其他层级
        for (const path of paths) {
            url += `/${path}`;
            if (breadcrumbNameMap[url]) {
                breadcrumbs.push(
                    <Breadcrumb.Item
                        key={url}
                        onClick={() => router.push(url)}
                        className={styles.breadcrumbItem}
                    >
                        {breadcrumbNameMap[url]}
                    </Breadcrumb.Item>
                );
            }
        }

        return breadcrumbs;
    };

    // 将 handleUserMenuClick 移到组件内部
    const handleUserMenuClick = ({ key }: { key: string }) => {
        switch (key) {
            case 'logout':
                // 处理登出逻辑
                console.log('logout');
                router.push('/');
                break;
            case 'profile':
                router.push('/user/profile');
                break;
            case 'settings':
                router.push('/user/settings');
                break;
        }
    };

    return (
        <Layout style={baseLayoutStyle}>
            <Suspense fallback={null}>
                <Sider
                    style={siderStyle}
                    collapsible
                    collapsed={collapsed}
                    onCollapse={setCollapsed}
                    width={200}
                    collapsedWidth={80}
                >
                    <div style={logoStyle} title='返回首页' onClick={() => router.push('/home')}>
                        <AcmeLogo />
                        {collapsed ? '' : '康悦诊所'}
                    </div>
                    <Menu
                        theme="dark"
                        defaultSelectedKeys={[router.pathname]}
                        defaultOpenKeys={['user', 'system']}
                        selectedKeys={[router.pathname]}
                        mode="inline"
                        items={items}
                        onClick={handleMenuClick}
                    />
                </Sider>
                <Layout style={collapsed ? mainContentCollapsedStyle : mainContentStyle}>
                    <div style={innerContentStyle}>
                        <Header className={styles.fixedHeader} style={{
                            padding: '0 24px',
                            width: `calc(100% - ${collapsed ? '80px' : '200px'})`, // 根据侧边栏宽度动态调整
                            background: '#ffffff',
                            display: 'flex',
                            justifyContent: 'space-between',
                            alignItems: 'center',
                            height: '64px',
                            transition: 'width 0.2s cubic-bezier(0.4, 0, 0.2, 1)', // 添加过渡效果
                        }}>
                            <div className={styles.headerLeft}>
                                <Breadcrumb style={{ margin: '16px 0' }}>
                                    {generateBreadcrumbs()}
                                </Breadcrumb>
                            </div>
                            <div className={styles.headerRight}>
                                <Dropdown
                                    menu={{
                                        items: userMenuItems,
                                        onClick: handleUserMenuClick,
                                    }}
                                    placement="bottomRight"
                                    arrow
                                    trigger={['click']} // 改为点击触发
                                >
                                    <Space className={styles.userInfo}>
                                        <span style={{ marginRight: 8 }}>龙龙</span>
                                        <Avatar
                                            size={40}
                                            src="https://api.dicebear.com/7.x/avataaars/svg?seed=Felix" // 使用 DiceBear API 生成头像
                                            style={{
                                                cursor: 'pointer',
                                                backgroundColor: '#87d068',
                                            }}
                                            alt="用户头像"
                                        />
                                    </Space>
                                </Dropdown>
                            </div>
                        </Header>
                        <Content style={{
                            margin: '60px 0 0 0',
                            background: blue1,
                            minHeight: 'calc(100vh - 60px - 69px)',
                            borderRadius: borderRadiusLG,
                            padding: '2px 18px 0 18px',
                            opacity: mounted ? 1 : 0, // 添加透明度过渡
                            transition: 'opacity 0.3s ease-in-out',
                        }}>
                            {/*<Breadcrumb style={{ margin: '16px 0' }}>*/}
                            {/*    {generateBreadcrumbs()}*/}
                            {/*</Breadcrumb>*/}
                            <div
                                style={{
                                    marginTop: 24,
                                    padding: 24,
                                    minHeight: 360,
                                    background: colorBgContainer,
                                    borderRadius: borderRadiusLG,
                                }}
                            >
                                <Component {...pageProps} />
                            </div>
                        </Content>
                        <Footer style={{
                            textAlign: 'center',
                            background: '#ffffff',
                            padding: '20px 0',
                            boxShadow: '0 -1px 2px rgba(0,0,0,0.03)', // 添加微妙的阴影
                        }}>
                            Long Long ©{new Date().getFullYear()} Created by LongCoding
                        </Footer>
                    </div>
                </Layout>
            </Suspense>
        </Layout>
    );
}
